package com.outfood.utils;

import com.alibaba.fastjson.JSON;
import com.outfood.config.WxGzhConfig;
import com.rys.common.json.JSONObject;
import com.rys.common.utils.StringUtils;
import lombok.Data;
import lombok.extern.log4j.Log4j2;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Log4j2
@Component
public class TokenUtils {
    
    @Resource
    RestTemplate restTemplate;
    @Resource
    RedisTemplate redisTemplate;

    @Resource
    WxGzhConfig wxGzhConfig;

    @PostConstruct
    public void deleteToken(){
        redisTemplate.delete("se_token");
    }
    
    public String getAccessTekn(){
        String seToken = (String) redisTemplate.opsForValue().get("se_token");
        if(StringUtils.isNotBlank(seToken)){
            return seToken;
        }
        ResponseEntity<String> forEntity = restTemplate.getForEntity("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+wxGzhConfig.getAppid()+"&secret="+wxGzhConfig.getSecret(), String.class);
        log.info("获取access返回数据为{}",forEntity.getBody());
        AccessToken body = JSON.parseObject(forEntity.getBody(),AccessToken.class);
        redisTemplate.opsForValue().set("se_token",body.getAccess_token(),body.getExpires_in(), TimeUnit.SECONDS);
        return body.access_token;
    }

    @Data
    public static class AccessToken{

        private String access_token;
        private Long expires_in ;

    }
}
